<?php

namespace GordenSong\Support;

trait PrefixTrait
{
	public function prefix(string $prefix, bool $required = false)
	{
		$prefix = trim($prefix . '.');
		$pieces = explode('.', $prefix);
		$reverses = array_reverse($pieces);
		foreach ($reverses as $revers) {
			$this->addPrefix($revers, $required);
		}
		return $this;
	}

	private function addPrefix(string $prefix, bool $required = false)
	{
		if (!empty($prefix)) {
			foreach ($this->rules as $key => $rule) {
				$this->rules[$this->keyWithPrefix($prefix, $key)] = $rule;

				unset($this->rules[$key]);
			}

			$this->rules = array_merge([
				$this->keyWithPrefix($prefix, '') => array_merge($required ? ['required'] : [], ['array']),
			], $this->rules);

			foreach ($this->attributes as $key => $attribute) {
				$this->attributes[$this->keyWithPrefix($prefix, $key)] = $attribute;

				unset($this->attributes[$key]);
			}
			foreach ($this->messages as $key => $message) {
				$this->messages[$this->keyWithPrefix($prefix, $key)] = $message;
			}
		}
		return $this;
	}

	protected function keyWithPrefix($prefix, $key): string
	{
		$prefix = rtrim($prefix, '.');
		if ($key) {
			$prefix .= '.' . $key;
		}
		return $prefix;
	}
}